package com.xian.zk.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

/**
 * @program: zoo-task
 * @description:
 * @author: liru.xian
 * @create: 2022-01-14 14:09
 **/

public class IpAddress {

    /**
     * 获取本机内网ip
     * @return
     * @throws UnknownHostException
     */
    private static String getIp() throws UnknownHostException {
        String ip = InetAddress.getLocalHost().getHostAddress();

        return ip;
    }

    /**
     * IP 地址校验的正则表达式
     */
    private static final Pattern IPV4_PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

    /**
     * 获取 IP 地址的服务列表
     */
    private static final String[] IPV4_SERVICES = {
            "http://checkip.amazonaws.com/",
            "https://ipv4.icanhazip.com/",
            "http://bot.whatismyipaddress.com/"
            // and so on ...
    };

    public static String get() {

        List<Callable<String>> callables = new ArrayList<>();
        for (String ipService : IPV4_SERVICES) {
            callables.add(() -> get(ipService));
        }

        ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            // 返回第一个成功获取的 IP
            return executorService.invokeAny(callables);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
        return null;
    }

    private static String get(String url) throws IOException {

        InputStream inputStream = null;
        InputStreamReader reader = null;
        BufferedReader in = null;
        try {
            inputStream = new URL(url).openStream();
            reader = new InputStreamReader(inputStream);
            in = new BufferedReader(reader);
            String ip = in.readLine();
            if (IPV4_PATTERN.matcher(ip).matches()) {
                return ip;
            } else {
                throw new IOException("invalid IPv4 address: " + ip);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (in != null) {
                in.close();
            }
        }
    }
}
